package com.sentrix.auto.printercenter.application;

import cn.hutool.core.collection.CollUtil;
import com.google.gson.Gson;
import com.sentrix.auto.printercenter.domain.entity.PrinterAgentEntity;
import com.sentrix.auto.printercenter.domain.entity.PrinterEntity;
import com.sentrix.auto.printercenter.infrastructure.agentserver.AgentClientManager;
import com.sentrix.auto.printercenter.infrastructure.agentserver.dto.BaseWebSocketResMsg;
import com.sentrix.auto.printercenter.infrastructure.agentserver.dto.CallMethodType;
import com.sentrix.auto.printercenter.infrastructure.agentserver.dto.PrinterNameMsg;
import com.sentrix.auto.printercenter.infrastructure.agentserver.dto.BaseQZPrintReq;
import com.sentrix.auto.printercenter.infrastructure.persistence.IPrinterRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PrinterAgentDetectionService {
    @Resource
    private AgentService agentService;
    @Resource
    private IPrinterRepository printerRepository;
    private final Gson gson = new Gson();


    @Transactional
    public void detectOfflineAndNewPrinters() {
        List<PrinterAgentEntity> agents = agentService.queryAll(Function.identity());
        log.info("待检测在线Agent数量：{}", agents.size());
        for (PrinterAgentEntity agent : agents) {
            if (!agent.getIsOnline()) {
                log.info("agent 离线：{}", agent.getCode());
                return;
            }
            //检测打印机
            detectPrinter(agent);
            //检测打印机状态
            detectPrinterStatus(agent);
        }
    }

    private void detectPrinterStatus(PrinterAgentEntity agent) {
        BaseQZPrintReq reqParam = new BaseQZPrintReq();
        reqParam.setCall(CallMethodType.PRINTERS_GET_STATUS);
        BaseWebSocketResMsg resMsg = AgentClientManager.instance().sendMessage(agent.getCode(), reqParam, 5);
        if (!resMsg.isSuccess()) {
            log.info("获取打印机状态失败，agent：{}，message:{}", agent.getCode(), resMsg.getResult());
            return;
        }
        if (StringUtils.isBlank(resMsg.getResult())) {
            return;
        }
    }

    private void detectPrinter(PrinterAgentEntity agent) {
        BaseQZPrintReq reqParam = new BaseQZPrintReq();
        reqParam.setCall(CallMethodType.PRINTERS_FIND);
        reqParam.setParams(Collections.EMPTY_MAP);
        BaseWebSocketResMsg resMsg = AgentClientManager.instance().sendMessage(agent.getCode(), reqParam, 5);
        if (!resMsg.isSuccess()) {
            log.info("获取打印机列表失败，agent：{}，message:{}", agent.getCode(), resMsg.getResult());
            return;
        }
        if (StringUtils.isBlank(resMsg.getResult())) {
            return;
        }
        PrinterNameMsg printerNameMsg = gson.fromJson(resMsg.getResult(), PrinterNameMsg.class);
        Map<String, PrinterEntity> printers = printerRepository.findByAgentCode(agent.getCode()).stream().collect(Collectors.toMap(PrinterEntity::getName, Function.identity()));
        List<PrinterEntity> printerEntities = new ArrayList<>();
        for (String printerName : printerNameMsg.getResult()) {
            PrinterEntity printer = printers.get(printerName);
            if (printer == null) {
                log.info("新增打印机：{}", printerName);
                printer = new PrinterEntity();
                printerEntities.add(printer);

                printer.setName(printerName);
                printer.setCode(UUID.randomUUID().toString());
                printer.setAgentCode(agent.getCode());
                printer.setAgentName(agent.getName());
                printer.setEnable(Boolean.TRUE);
                printer.setIsOnline(Boolean.FALSE);
            }
        }
        if (CollUtil.isNotEmpty(printerEntities)) {
            printerRepository.saveBatch(printerEntities);
        }
    }
}
